﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using CPlatePrintSys.Domain.Models;
using CPlatePrintSys.Domain.Services;
using CPlatePrintSys.Infrastructure.Helpers;
using CPlatePrintSys.Win.Controls;
using Prism.Commands;
using Prism.Dialogs;
using Prism.Events;
using Prism.Mvvm;

namespace CPlatePrintSys.Win.ViewModels
{
    public class AddBaseInfoViewModel : BindableBase
    {
        private readonly IWorkSpaceService _workSpaceService;
        private readonly IEventAggregator _eventAggregator;

        // 完整工作目录树
        private List<WorkSpaceNodeViewModel> _fullWorkDirectoryTree;

        public string Title { get; set; } = "添加基础信息";

        public event Action<IDialogResult> RequestClose;

      
        // 转换为BaseInfoTreeNode的树形数据
        public ObservableCollection<BaseInfoTreeNode> BaseInfoTreeNodes
        {
            get;
            private set;
        }

        // 加载状态
        private bool _isLoading;
        public bool IsLoading
        {
            get => _isLoading;
            set => SetProperty(ref _isLoading, value);
        }

        // 命令
        public DelegateCommand ConfirmBaseInfoCommand { get; set; }
        public DelegateCommand CancelCommand { get; set; }
        public DelegateCommand LoadFullDirectoryTreeCommand { get; set; }

        public AddBaseInfoViewModel(IWorkSpaceService workSpaceService, IEventAggregator eventAggregator)
        {
            _workSpaceService = workSpaceService;
            _eventAggregator = eventAggregator;

            _fullWorkDirectoryTree = new List<WorkSpaceNodeViewModel>();
            BaseInfoTreeNodes = new ObservableCollection<BaseInfoTreeNode>();

            ConfirmBaseInfoCommand = new DelegateCommand(ConfirmBaseInfo, CanConfirmBaseInfo);
            CancelCommand = new DelegateCommand(Cancel);
            LoadFullDirectoryTreeCommand = new DelegateCommand(async () => await LoadFullDirectoryTreeAsync());

            // 初始化
            InitializeAsync();
        }

        private async void InitializeAsync()
        {
            try
            {
                IsLoading = true;

                // 加载完整工作目录树
                await LoadFullDirectoryTreeAsync();
            }
            catch (Exception ex)
            {
                AMLog.Error(ex.Message);
            }
            finally
            {
                IsLoading = false;
            }
        }

        private async Task LoadFullDirectoryTreeAsync()
        {
            try
            {
                var fullTree = await _workSpaceService.GetFullWorkDirectoryTreeAsync();
                System.Diagnostics.Debug.WriteLine($"从服务获取数据: fullTree.Count={fullTree?.Count ?? 0}");
                
                var viewModels = WorkSpaceNodeViewModel.CreateFromWorkSpaceNodes(fullTree);
                System.Diagnostics.Debug.WriteLine($"创建ViewModel: viewModels.Count={viewModels?.Count ?? 0}");
                
                _fullWorkDirectoryTree.Clear();
                foreach (var vm in viewModels)
                {
                    _fullWorkDirectoryTree.Add(vm);
                }

                // 获取当前工作空间的节点，用于设置默认选中状态
                var currentWorkSpace = _workSpaceService.GetCurrentWorkSpace();
                var currentWorkSpaceNodeNames = new HashSet<string>();
                
                System.Diagnostics.Debug.WriteLine($"当前工作空间: {(currentWorkSpace != null ? currentWorkSpace.Name : "null")}");
                System.Diagnostics.Debug.WriteLine($"当前工作空间ID: {(currentWorkSpace != null ? currentWorkSpace.Id.ToString() : "null")}");
                System.Diagnostics.Debug.WriteLine($"当前工作空间节点数量: {(currentWorkSpace?.WorkSpaceNodes?.Count ?? 0)}");
                
                if (currentWorkSpace?.WorkSpaceNodes != null && currentWorkSpace.WorkSpaceNodes.Count > 0)
                {
                    CollectWorkSpaceNodeNames(currentWorkSpace.WorkSpaceNodes, currentWorkSpaceNodeNames);
                    System.Diagnostics.Debug.WriteLine($"收集到的工作空间节点数量: {currentWorkSpaceNodeNames.Count}");
                    System.Diagnostics.Debug.WriteLine($"收集到的工作空间节点名称: {string.Join(", ", currentWorkSpaceNodeNames)}");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("当前没有工作空间或工作空间为空");
                }

                // 转换为BaseInfoTreeNode格式，并设置默认选中状态
                var convertedNodes = ConvertToBaseInfoTreeNodes(_fullWorkDirectoryTree, currentWorkSpaceNodeNames);
                BaseInfoTreeNodes.Clear();
                foreach (var node in convertedNodes)
                {
                    BaseInfoTreeNodes.Add(node);
                }
                
                // 调试信息
                System.Diagnostics.Debug.WriteLine($"转换完成: FullWorkDirectoryTree.Count={_fullWorkDirectoryTree.Count}, BaseInfoTreeNodes.Count={BaseInfoTreeNodes.Count}");
                
                // 统计选中的节点数量
                int selectedCount = CountSelectedNodes(BaseInfoTreeNodes);
                System.Diagnostics.Debug.WriteLine($"默认选中的节点数量: {selectedCount}");
            }
            catch (Exception ex)
            {
                AMLog.Error(ex.Message);
            }
        }

        private List<BaseInfoTreeNode> ConvertToBaseInfoTreeNodes(List<WorkSpaceNodeViewModel> workSpaceNodes, HashSet<string> currentWorkSpaceNodeNames)
        {
            var result = new List<BaseInfoTreeNode>();
            
            foreach (var node in workSpaceNodes)
            {
                var baseInfoNode = ConvertWorkSpaceNodeToBaseInfoNode(node, currentWorkSpaceNodeNames);
                result.Add(baseInfoNode);
            }
            
            return result;
        }

        private BaseInfoTreeNode ConvertWorkSpaceNodeToBaseInfoNode(WorkSpaceNodeViewModel workSpaceNode, HashSet<string> currentWorkSpaceNodeNames)
        {
            var baseInfoNode = new BaseInfoTreeNode(workSpaceNode.Name);
            
            // 根据当前工作空间节点设置选中状态
            bool isInCurrentWorkSpace = currentWorkSpaceNodeNames.Contains(workSpaceNode.Name);
            baseInfoNode.IsChecked = isInCurrentWorkSpace;
            
            // 调试信息：记录选中状态
            if (isInCurrentWorkSpace)
            {
                System.Diagnostics.Debug.WriteLine($"节点 '{workSpaceNode.Name}' 设置为选中状态");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine($"节点 '{workSpaceNode.Name}' 设置为未选中状态");
            }
            
            // 订阅选择状态变更事件
            baseInfoNode.PropertyChanged += OnBaseInfoTreeNodePropertyChanged;
            
            if (workSpaceNode.Children != null && workSpaceNode.Children.Count > 0)
            {
                foreach (var child in workSpaceNode.Children)
                {
                    var childBaseInfoNode = ConvertWorkSpaceNodeToBaseInfoNode(child, currentWorkSpaceNodeNames);
                    baseInfoNode.Children.Add(childBaseInfoNode);
                }
            }
            
            return baseInfoNode;
        }

        private void OnBaseInfoTreeNodePropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(BaseInfoTreeNode.IsChecked))
            {
                // 当选择状态改变时，重新评估命令的可执行性
                ConfirmBaseInfoCommand.RaiseCanExecuteChanged();
            }
        }

        private bool CanConfirmBaseInfo()
        {
            return BaseInfoTreeNodes != null && BaseInfoTreeNodes.Any(n => n.IsChecked == true || HasSelectedBaseInfoChildren(n));
        }

        private bool HasSelectedBaseInfoChildren(BaseInfoTreeNode node)
        {
            if (node.Children == null || node.Children.Count == 0) return false;
            
            foreach (var child in node.Children)
            {
                if (child.IsChecked == true || HasSelectedBaseInfoChildren(child))
                {
                    return true;
                }
            }
            return false;
        }

        private bool HasSelectedChildren(WorkSpaceNodeViewModel node)
        {
            if (node.Children == null) return false;
            
            foreach (var child in node.Children)
            {
                if (child.IsSelected || HasSelectedChildren(child))
                {
                    return true;
                }
            }
            return false;
        }

        private async void ConfirmBaseInfo()
        {
            try
            {
                IsLoading = true;

                // 收集选中的节点
                var selectedNodes = CollectSelectedBaseInfoNodes(BaseInfoTreeNodes);
                
                // 调试信息：打印层次结构
                System.Diagnostics.Debug.WriteLine($"创建的工作空间节点数量: {selectedNodes.Count}");
                foreach (var node in selectedNodes)
                {
                    PrintNodeHierarchy(node, 0);
                }
                
                // 清除Parent引用以避免JSON序列化循环引用问题
                ClearParentReferences(selectedNodes);

                // 创建工作空间
                var workSpace = new WorkSpace
                {
                    Name =  "default",
                    Description = "",
                    WorkSpaceNodes = selectedNodes,
                    CreatedBy = GetCurrentUsername()
                };

                var createdWorkSpace = await _workSpaceService.CreateWorkSpaceAsync(workSpace);

                // 设置为当前工作空间
                _workSpaceService.SetCurrentWorkSpace(createdWorkSpace);

                // 保存到本地配置
                await _workSpaceService.SaveWorkSpaceToLocalConfigAsync(createdWorkSpace);

                // 关闭对话框
                var result = new DialogResult(ButtonResult.OK);
                result.Parameters.Add("WorkSpace", createdWorkSpace);
                RequestClose?.Invoke(result);
            }
            catch (Exception ex)
            {
                
                AMLog.Error(ex.Message);
            }
            finally
            {
                IsLoading = false;
            }
        }

        private List<WorkSpaceNode> CollectSelectedBaseInfoNodes(ObservableCollection<BaseInfoTreeNode> tree)
        {
            var selectedNodes = new List<WorkSpaceNode>();
            var nodeIdCounter = 1; // 用于生成唯一的节点ID
            
            foreach (var node in tree)
            {
                var workSpaceNode = ConvertBaseInfoTreeNodeToWorkSpaceNode(node, null, ref nodeIdCounter);
                if (workSpaceNode != null)
                {
                    selectedNodes.Add(workSpaceNode);
                }
            }

            return selectedNodes;
        }

        private WorkSpaceNode ConvertBaseInfoTreeNodeToWorkSpaceNode(BaseInfoTreeNode baseInfoNode, WorkSpaceNode parentNode, ref int nodeIdCounter)
        {
            // 如果当前节点没有被选中，且没有选中的子节点，则跳过
            if (baseInfoNode.IsChecked != true && !HasSelectedBaseInfoChildren(baseInfoNode))
            {
                return null;
            }

            // 根据层级关系确定节点类型
            string nodeType = DetermineNodeTypeByLevel(parentNode);

            var workSpaceNode = new WorkSpaceNode
            {
                Id = nodeIdCounter++,
                Name = baseInfoNode.Name,
                NodeType = nodeType, // 根据层级关系确定类型
                NodeValue = baseInfoNode.Name,
                SortOrder = 0,
                IsSelected = baseInfoNode.IsChecked == true,
                Parent = parentNode
            };

            // 如果有父节点，设置父节点ID
            if (parentNode != null)
            {
                workSpaceNode.ParentNodeId = parentNode.Id;
            }

            // 处理子节点
            if (baseInfoNode.Children != null && baseInfoNode.Children.Count > 0)
            {
                var childNodes = new List<WorkSpaceNode>();
                foreach (var child in baseInfoNode.Children)
                {
                    var childWorkSpaceNode = ConvertBaseInfoTreeNodeToWorkSpaceNode(child, workSpaceNode, ref nodeIdCounter);
                    if (childWorkSpaceNode != null)
                    {
                        childNodes.Add(childWorkSpaceNode);
                    }
                }
                workSpaceNode.Children = childNodes;
            }

            return workSpaceNode;
        }

        /// <summary>
        /// 根据层级关系确定节点类型
        /// 层级关系：船号 -> Lot号 -> 加工序列
        /// </summary>
        /// <param name="parentNode">父节点，null表示根节点</param>
        /// <returns>节点类型</returns>
        private string DetermineNodeTypeByLevel(WorkSpaceNode parentNode)
        {
            if (parentNode == null)
            {
                // 第1层：船号
                return "Ship";
            }
            else if (parentNode.NodeType == "Ship")
            {
                // 第2层：LOT号
                return "Lot";
            }
            else if (parentNode.NodeType == "Lot")
            {
                // 第3层：加工序列
                return "Sequence";
            }
            else
            {
                // 其他情况，默认为BaseInfo
                return "BaseInfo";
            }
        }

        /// <summary>
        /// 根据节点名称确定节点类型（已废弃，保留用于向后兼容）
        /// </summary>
        [Obsolete("此方法已废弃，请使用DetermineNodeTypeByLevel方法")]
        private string DetermineNodeType(string nodeName)
        {
            // 根据节点名称确定节点类型
            // 这里可以根据实际的命名规则进行调整
            if (nodeName.StartsWith("N") && nodeName.Length >= 4)
            {
                return "Ship"; // 船号 (如 N1071, N11519)
            }
            else if (nodeName.StartsWith("A") && nodeName.Length >= 3)
            {
                return "Lot"; // 批次号 (如 A10, A101A)
            }
            else if (nodeName.StartsWith("7P") || nodeName.StartsWith("8P") || 
                     nodeName.StartsWith("3P") || nodeName.StartsWith("4P") ||
                     nodeName.StartsWith("5P") || nodeName.StartsWith("6P") ||
                     nodeName.StartsWith("9P") || nodeName.StartsWith("0P"))
            {
                return "Sequence"; // 序列号 (如 3PS, 7PA001, 8PA002)
            }
            else
            {
                return "BaseInfo"; // 默认类型
            }
        }

        private void PrintNodeHierarchy(WorkSpaceNode node, int level)
        {
            var indent = new string(' ', level * 2);
            System.Diagnostics.Debug.WriteLine($"{indent}ID: {node.Id}, Name: {node.Name}, Type: {node.NodeType}, ParentId: {node.ParentNodeId}, IsSelected: {node.IsSelected}, Children: {node.Children?.Count ?? 0}");
            
            if (node.Children != null)
            {
                foreach (var child in node.Children)
                {
                    PrintNodeHierarchy(child, level + 1);
                }
            }
        }

        private void ClearParentReferences(List<WorkSpaceNode> nodes)
        {
            foreach (var node in nodes)
            {
                // 清除Parent引用，保留ParentNodeId用于重建关系
                node.Parent = null;
                
                if (node.Children != null && node.Children.Count > 0)
                {
                    ClearParentReferences(node.Children);
                }
            }
        }

        private void CollectWorkSpaceNodeNames(List<WorkSpaceNode> nodes, HashSet<string> nodeNames)
        {
            foreach (var node in nodes)
            {
                if (!string.IsNullOrEmpty(node.Name))
                {
                    nodeNames.Add(node.Name);
                }
                
                if (node.Children != null && node.Children.Count > 0)
                {
                    CollectWorkSpaceNodeNames(node.Children, nodeNames);
                }
            }
        }

        private int CountSelectedNodes(ObservableCollection<BaseInfoTreeNode> nodes)
        {
            int count = 0;
            foreach (var node in nodes)
            {
                if (node.IsChecked == true)
                {
                    count++;
                }
                
                if (node.Children != null && node.Children.Count > 0)
                {
                    count += CountSelectedNodes(new ObservableCollection<BaseInfoTreeNode>(node.Children));
                }
            }
            return count;
        }

        private List<WorkSpaceNode> CollectSelectedNodes(List<WorkSpaceNodeViewModel> tree)
        {
            var selectedNodes = new List<WorkSpaceNode>();
            
            foreach (var node in tree)
            {
                if (node.IsSelected)
                {
                    var selectedNode = new WorkSpaceNode
                    {
                        Name = node.Name,
                        NodeType = node.NodeType,
                        NodeValue = node.NodeValue,
                        SortOrder = node.SortOrder
                    };
                    selectedNodes.Add(selectedNode);
                }

                if (node.Children != null && node.Children.Any())
                {
                    var childSelectedNodes = CollectSelectedNodes(new List<WorkSpaceNodeViewModel>(node.Children));
                    selectedNodes.AddRange(childSelectedNodes);
                }
            }

            return selectedNodes;
        }

        private string GetCurrentUsername()
        {
            // 从应用程序属性中获取当前用户
            if (App.Current.Properties.Contains("CurrentUser"))
            {
                var user = App.Current.Properties["CurrentUser"] as User;
                return user?.Username ?? "Unknown";
            }
            return "Unknown";
        }

        private void Cancel()
        {
            // 清理事件订阅
            UnsubscribeFromBaseInfoTreeNodes();
            RequestClose?.Invoke(new DialogResult(ButtonResult.Cancel));
        }

        private void UnsubscribeFromBaseInfoTreeNodes()
        {
            if (BaseInfoTreeNodes != null)
            {
                foreach (var node in BaseInfoTreeNodes)
                {
                    UnsubscribeFromNode(node);
                }
            }
        }

        private void UnsubscribeFromNode(BaseInfoTreeNode node)
        {
            if (node != null)
            {
                node.PropertyChanged -= OnBaseInfoTreeNodePropertyChanged;
                
                if (node.Children != null)
                {
                    foreach (var child in node.Children)
                    {
                        UnsubscribeFromNode(child);
                    }
                }
            }
        }
    }
}
